package com.ll.domain.pk.base.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ll.app.api.req.ListPkReqDTO;
import com.ll.app.api.req.UpdateStatusPkReqDTO;
import com.ll.base.dto.IdDTO;
import com.ll.base.exception.CustomRunTimeException;
import com.ll.base.util.DateUtil;
import com.ll.base.util.ScalarUtil;
import com.ll.dal.mapper.PkMapper;
import com.ll.dal.po.PkPO;
import com.ll.domain.pk.base.PkBaseService;
import com.ll.domain.pk.convert.PkConvert;
import com.ll.domain.pk.dto.PkDTO;
import com.ll.domain.pk.enums.PkResultEnum;
import com.ll.domain.pk.enums.PkStatusEnum;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@RequiredArgsConstructor
public class PkBaseServiceImpl extends ServiceImpl<PkMapper, PkPO> implements PkBaseService {

    private final PkMapper pkMapper;


    @Override
    public PkPO getTodayPkBySourceId(Long tenantId, Long sourceId) {
        PkPO pkPO = pkMapper.selectOne(new LambdaQueryWrapper<PkPO>()
                .eq(PkPO::getSourceId, sourceId)
                .eq(PkPO::getTenantId, tenantId)
                .ge(PkPO::getCtime, DateUtil.startDate())
        );
        return pkPO;
    }

    @Override
    public PkPO getTodayPkByTargetId(Long tenantId, Long targetId) {
        PkPO pkPO = pkMapper.selectOne(new LambdaQueryWrapper<PkPO>()
                .eq(PkPO::getTargetId, targetId)
                .eq(PkPO::getTenantId, tenantId)
                .ge(PkPO::getCtime, DateUtil.startDate())
        );
        return pkPO;
    }

    @Override
    public List<PkPO>  getPkIngById(Long tenantId, Long id) {
        List<PkPO> pkPO = pkMapper.selectList(new LambdaQueryWrapper<PkPO>()
                .eq(PkPO::getResult, PkResultEnum.未处理)
                .eq(PkPO::getTenantId, tenantId)
                .and(r -> r.eq(PkPO::getSourceId, id).or(k -> k.eq(PkPO::getTargetId, id)))
        );
        return pkPO;
    }

    @Override
    public List<PkPO> list(ListPkReqDTO dto) {
        List<PkPO> pkPO = pkMapper.selectList(new LambdaQueryWrapper<PkPO>()
                .eq(PkPO::getTenantId, dto.getTenantId())
                .eq(dto.getResult() != null ,PkPO::getResult, dto.getResult())
                .eq(dto.getStatus() != null ,PkPO::getStatus, dto.getStatus())
                .eq(ScalarUtil.isNotEmpty(dto.getTargetId()), PkPO::getTargetId, dto.getTargetId())
                .and(ScalarUtil.isNotEmpty(dto.getUserId()), r -> r.eq(PkPO::getSourceId, dto.getUserId()).or(k -> k.eq(PkPO::getTargetId, dto.getUserId())))
        );
        return pkPO;
    }


    @Override
    public PkPO getById(Long id, boolean checkNull) {
        PkPO pkPO = pkMapper.selectById(id);
        if(checkNull){
            CustomRunTimeException.checkNull(pkPO,"PK数据不存在");
        }
        return pkPO;
    }
}
